<template>
  <a-menu
    mode="inline"
    theme="dark"
    v-model:selectedKeys="selectedKeys"
    :inline-collapsed="collapsed"
    @select="handleSelect"
    @openChange="onOpenChange"
    :open-keys="openKeys"
  >
    <sideItem v-for="v in routerChildren" :key="v.key" :item="v" />
  </a-menu>
</template>
<script>
import { reactive, toRefs, ref, inject, watch, toRaw, } from "vue"
import sideItem from './sideItem.vue'
import routerChildren from "../../router/routerChildren"
export default {
  name: 'SubMenu',
  components: {
    sideItem,
  },
  props: ['collapsed'],
  setup (props, context) {
    const state = reactive({
      rootSubmenuKeys: ['1', '2', '3', '4', '5', '6', '7', '8'],
      openKeys: ['1'],
      selectedKeys: ['1-1'],
    });
    const handleSelect = ({ item, key, selectedKeys }) => {
      // console.log(item, key, selectedKeys)
    }
    const filter = (arr, data, array) => {
      arr.forEach((v, i) => {
        if (data.includes(v.path)) {
          array.push(v.key)
        }
        if (v.children && v.children.length) {
          filter(v.children, data, array)
        }

      });
      return array
    }
    const path = inject('path')
    watch(path, (to, from) => {
      let pathArr = filter(routerChildren, toRaw(to), [])
      if (pathArr && pathArr.length) {
        if (pathArr.length == 1) {
          state.openKeys = pathArr

        } else {
          state.selectedKeys = [pathArr.pop()]
          state.openKeys = pathArr
        }
      }
    }, { immediate: true })
    const onOpenChange = (openKeys) => {
      const latestOpenKey = openKeys.find(key => state.openKeys.indexOf(key) === -1);
      state.openKeys = latestOpenKey ? [latestOpenKey] : [];
    }
    return {
      handleSelect,
      routerChildren,
      onOpenChange,
      path,
      ...toRefs(state),
    }
  }
}
</script>

<style lang="scss" scoped>
//防止左侧菜单溢出省略号
/deep/.ant-menu-title-content {
  display: block;
}
</style>
